<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 面包屑,路径导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{$route.query.id ? "修改文章" :"发布文章"}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form ref="publishForm" :model="article" label-width="60px" :rules="formRules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
          <el-tiptap height="500px" placeholder="请输入内容" v-model="article.content" :extensions="extensions" />
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择活动区域">
            <el-option
              :label="channel.name"
              :value="channel.id"
              v-for="(channel, index) in channels"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPublish(false)">发表</el-button>
          <el-button @click="onPublish(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  getArticlesChannels,
  addArticle,
  updateArticle,
  getArticle
} from "@/api/article";
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Fullscreen,
  Image,
} from "element-tiptap";
import {uploadImage } from "@/api/image"
export default {
  name: "",
  components: {
    // "el-tiptap": ElementTiptap
  },
  props: {},
  data() {
    return {
      article: {
        title: "", // 文章标题
        content: "", // 文章内容
        cover: {
          // 封面
          type: 0, // -1:自动，0：无图，1：一张，3：三张
          images: [] // 图片地址
        },
        channel_id: null
      },
      channels: [], // 文章频道列表
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 3 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new Image({
            // 自定义图片上传。默认生成base64字符串
            uploadRequest(file) {
                console.log("upload")
                const fd = new FormData()
                fd.append('image',file)
                return uploadImage(fd).then(res => {
                    return res.data.data.url
                })
            }
        }),
        new Fullscreen(),
        
      ],
      formRules: {
        title: [
          {required: true,message: '请输入标题',trigger: 'blur'},
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        content: [
          {// required: true,message: '请输入内容',trigger: 'change'
            validator (rule,value,callback){
              if(value ==="<p></p>"){
                callback (new Error('请输入内容'))
              }else{
                callback()
              }
            }
          }
        ],
        channel_id: [
          {required: true,message: '请选择频道'}
        ]
      }
    };
  },
  computed: {},
  watch: {},
  created() {
    // 发布和编辑公用同一个组件，所以这里判断请求路径中是否携带id参数
    this.loadChannels();
    if (this.$route.query.id) {
      this.loadarticle();
    }
  },
  mounted() {},
  methods: {
    onPublish(draft = false) {
      // 表单验证
      // this.$refs['publish-form'].validate(valid =>{
      //   if(!valid){

      //     return
      //   }else{
      //     // 验证通过，提交表单
      //   }
      // })
      // 提交表单
      // 判断是修改还是新增
      const articleId = this.$route.query.id;
      if (articleId) {
        // 执行修改操作
        updateArticle(articleId, this.article, draft).then(res => {
          //   console.log(res);
          this.$message({
            message: `${draft ? "存入草稿" : "发布"}成功`,
            type: "success"
          });
        });
        // 跳转到内容管理页面
        this.$router.push("/article");
      } else {
        addArticle(this.article, draft).then(res => {
          // console.log(res)
          this.$message({
            message: `${draft ? "存入草稿" : "发布"}成功`,
            type: "success"
          });
        });
        // 跳转到内容管理页面
        this.$router.push("/article");
      }
    },
    loadChannels() {
      getArticlesChannels().then(res => {
        // console.log(res)
        this.channels = res.data.data.channels;
      });
    },
    // 修改文章-加载文章内容
    loadarticle() {
      getArticle(this.$route.query.id).then(res => {
        // console.log(res)
        this.article = res.data.data;
      });
    }
  }
};
</script>

<style scoped lang="less">
</style>